'use client';

import { useConnection } from '@solana/wallet-adapter-react';
import { useState } from 'react';

export function NetworkDiagnostic() {
  const { connection } = useConnection();
  const [isOpen, setIsOpen] = useState(false);
  const [diagnosticResults, setDiagnosticResults] = useState<{
    rpcUrl: string;
    connectivity: 'checking' | 'success' | 'failed';
    latency?: number;
    blockHeight?: number;
    error?: string;
  } | null>(null);

  const runDiagnostic = async () => {
    setDiagnosticResults({
      rpcUrl: connection.rpcEndpoint,
      connectivity: 'checking',
    });

    try {
      const startTime = Date.now();
      
      // 测试基本连接
      await connection.getSlot(); // 测试连接
      const latency = Date.now() - startTime;
      
      // 获取区块高度
      const blockHeight = await connection.getBlockHeight();
      
      setDiagnosticResults({
        rpcUrl: connection.rpcEndpoint,
        connectivity: 'success',
        latency,
        blockHeight,
      });
    } catch (error) {
      setDiagnosticResults({
        rpcUrl: connection.rpcEndpoint,
        connectivity: 'failed',
        error: error instanceof Error ? error.message : '未知错误',
      });
    }
  };

  if (!isOpen) {
    return (
      <button
        onClick={() => setIsOpen(true)}
        className="fixed bottom-6 left-6 bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors shadow-lg"
      >
        🔧 网络诊断
      </button>
    );
  }

  return (
    <div className="fixed bottom-6 left-6 bg-gray-800 rounded-lg shadow-lg border border-gray-600 p-4 w-80 z-50">
      <div className="flex justify-between items-center mb-3">
        <h3 className="font-medium text-white">网络连接诊断</h3>
        <button
          onClick={() => setIsOpen(false)}
          className="text-gray-400 hover:text-gray-200"
        >
          ✕
        </button>
      </div>

      <div className="space-y-3">
        <div>
          <label className="text-sm text-gray-300">RPC 端点:</label>
          <div className="text-sm font-mono bg-gray-700 text-gray-200 p-2 rounded break-all">
            {connection.rpcEndpoint}
          </div>
        </div>

        <button
          onClick={runDiagnostic}
          disabled={diagnosticResults?.connectivity === 'checking'}
          className="w-full bg-blue-500 hover:bg-blue-600 disabled:bg-blue-300 text-white py-2 px-4 rounded font-medium transition-colors"
        >
          {diagnosticResults?.connectivity === 'checking' ? '检测中...' : '开始诊断'}
        </button>

        {diagnosticResults && (
          <div className="border-t border-gray-600 pt-3 space-y-2">
            <div className="flex justify-between">
              <span className="text-sm text-gray-300">连接状态:</span>
              <span className={`text-sm font-medium ${
                diagnosticResults.connectivity === 'success' 
                  ? 'text-green-400' 
                  : diagnosticResults.connectivity === 'failed'
                  ? 'text-red-400'
                  : 'text-yellow-400'
              }`}>
                {diagnosticResults.connectivity === 'success' && '✅ 正常'}
                {diagnosticResults.connectivity === 'failed' && '❌ 失败'}
                {diagnosticResults.connectivity === 'checking' && '⏳ 检测中'}
              </span>
            </div>

            {diagnosticResults.latency && (
              <div className="flex justify-between">
                <span className="text-sm text-gray-300">延迟:</span>
                <span className={`text-sm font-medium ${
                  diagnosticResults.latency < 1000 ? 'text-green-400' :
                  diagnosticResults.latency < 3000 ? 'text-yellow-400' : 'text-red-400'
                }`}>
                  {diagnosticResults.latency}ms
                </span>
              </div>
            )}

            {diagnosticResults.blockHeight && (
              <div className="flex justify-between">
                <span className="text-sm text-gray-300">区块高度:</span>
                <span className="text-sm font-medium text-white">
                  {diagnosticResults.blockHeight.toLocaleString()}
                </span>
              </div>
            )}

            {diagnosticResults.error && (
              <div className="bg-red-900/30 border border-red-600 rounded p-2">
                <div className="text-sm text-red-400 font-medium mb-1">错误详情:</div>
                <div className="text-xs text-red-300 break-words">
                  {diagnosticResults.error}
                </div>
              </div>
            )}
          </div>
        )}

        <div className="text-xs text-gray-400 border-t border-gray-600 pt-2">
          <div className="font-medium mb-1">问题排查建议:</div>
          <ul className="space-y-1">
            <li>• 检查网络连接是否稳定</li>
            <li>• 尝试刷新页面重新连接</li>
            <li>• 确认 Phantom 钱包网络设置</li>
            <li>• 联系技术支持获取帮助</li>
          </ul>
        </div>
      </div>
    </div>
  );
}
